package pers.cj.pdos.controller.analysis;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.performanceAnalysis.ExcelPerformanceAnalysis;
import pers.cj.pdos.excel.performanceAnalysis.ExcelPerformanceAnalysisGoods;
import pers.cj.pdos.excel.performanceAnalysis.ExcelPerformanceAnalysisOrder;
import pers.cj.pdos.service.IPerformanceAnalysisService;
import pers.cj.pdos.service.IStoreService;
import pers.cj.pdos.service.IUserService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.DateUtils;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/financeCount")
public class PerformanceAnalysisController extends BaseController {
    @Autowired
    IPerformanceAnalysisService performanceAnalysisService;
    @Autowired
    IUserService userService;
    @Autowired
    IStoreService storeService;

    @RequiresPermissions("performanceAnalysis:query")
    @RequestMapping("/performanceAnalysis")
    public String profitAnalysis(Model model, String storeId, String date1, String date2) {
        model.addAttribute("storeId",storeId);
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);
        return "analysis/performance/performanceAnalysis";
    }

    @RequiresPermissions("performanceAnalysis:query")
    @RequestMapping("/performanceAnalysisDetail")
    public String saleAnalysisDetailGoods(Model model, String userId, String storeId, String date1, String date2) {
        model.addAttribute("userId",userId);
        model.addAttribute("storeId",storeId);
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);

        model.addAttribute("user",  userService.getById(userId));

        if (!Utils.isEmpty(storeId)) {
            model.addAttribute("storeName",storeService.getById(storeId).getName());
        }

        return "analysis/performance/performanceAnalysisDetail";
    }

    @ResponseBody
    @RequestMapping("/performanceAnalysis/getAllTotalData")
    public ResponseData getAllTotalData(String storeId,
                                        String date1,
                                        String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        Map map = performanceAnalysisService.getTotalData(company.getId(), PdosUtils.getViewOtherStoreId(userVo,storeId), Utils.genDate(date1), Utils.genDate(date2));

        Map highSaleUser = performanceAnalysisService.getHighSaleUser(company.getId(), PdosUtils.getViewOtherStoreId(userVo,storeId), Utils.genDate(date1), Utils.genDate(date2));

        map.put("highSaleUser", highSaleUser);
        return ResponseData.success(map);
    }

    @ResponseBody
    @RequestMapping("/performanceAnalysis/listUserData")
    public ResponseList listUserData(String page,
                                      String limit,
                                      String storeId,
                                      String date1,
                                      String date2,
                                      String filterZero,
                                      String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<PerformanceAnalysis> list = performanceAnalysisService.listUserData(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                null);

        Long count = performanceAnalysisService.countUserData(company.getId(),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                null);

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/performanceAnalysis/listDetailByOrder")
    public ResponseList listDetailByOrder(String page,
                                          String limit,
                                          String userId,
                                          String storeId,
                                          String date1,
                                          String date2,
                                          String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<PerformanceAnalysis> list = performanceAnalysisService.listDetailByOrder(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        Long count = performanceAnalysisService.countDetailByOrder(company.getId(),
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/performanceAnalysis/listDetailByGoods")
    public ResponseList listDetailByGoods(String page,
                                          String limit,
                                          String userId,
                                          String storeId,
                                          String date1,
                                          String date2,
                                          String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<PerformanceAnalysis> list = performanceAnalysisService.listDetailByGoods(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        Long count = performanceAnalysisService.countDetailByGoods(company.getId(),
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }



    @ResponseBody
    @RequiresPermissions("performanceAnalysis:export")
    @RequestMapping("/performanceAnalysis/export")
    public ResponseData export(String storeId,
                                     String date1,
                                     String date2,
                                     String filterZero,
                                     String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<PerformanceAnalysis> list = performanceAnalysisService.listUserData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId));


        List<ExcelPerformanceAnalysis> excelList = new ArrayList<>();
        for (PerformanceAnalysis entity : list) {
            ExcelPerformanceAnalysis excel = new ExcelPerformanceAnalysis();
            excel.setName(entity.getName());
            excel.setUsername(entity.getUsername());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setRatio(PdosUtils.getNumber(entity.getRatio(), businessSet)+"%");
            excel.setAvgAmount(PdosUtils.getPrice(entity.getAvgAmount(), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excel.setRefundNum(PdosUtils.getNumber(entity.getRefundNum(), businessSet));
            excel.setRefundAmt(PdosUtils.getPrice(entity.getRefundAmt(), businessSet));
            excelList.add(excel);
        }


        String excelName = "业绩统计列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";

        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelPerformanceAnalysis.class);
            sheet1.setSheetName("业绩统计列表");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("performanceAnalysis:export")
    @RequestMapping("/performanceAnalysis/exportDetailByOrder")
    public ResponseData exportDetailByOrder(String userId,
                                     String storeId,
                                     String date1,
                                     String date2,
                                     String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<PerformanceAnalysis> list = performanceAnalysisService.listDetailByOrder(company.getId(),
                null,
                null,
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));


        List<ExcelPerformanceAnalysisOrder> excelList = new ArrayList<>();
        for (PerformanceAnalysis entity : list) {
            ExcelPerformanceAnalysisOrder excel = new ExcelPerformanceAnalysisOrder();
            excel.setNo(entity.getNo());
            excel.setDate(entity.getDate());
            excel.setBuss(entity.getType()==1 ? "销售":"销售退货");
            excel.setCustomName(entity.getCustomName());

            String goods = "";
            if (!Utils.isEmpty(entity.getGoodsList())) {
                for (Goods vo : entity.getGoodsList()) {
                    goods += vo.getName() + "、";
                }
            }
            if (!Utils.isEmpty(entity.getPacketList())) {
                for (Packet vo : entity.getPacketList()) {
                    goods += vo.getName() + "、";
                }
            }

            if (!Utils.isEmpty(goods)) {
                goods = goods.substring(0, goods.length() - 1);
            }

            excel.setGoods(goods);

            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setDiscountAmt(PdosUtils.getPrice(entity.getDiscountAmt(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }


        String excelName = "业绩统计按单据列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";

        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelPerformanceAnalysisOrder.class);
            sheet1.setSheetName("业绩统计按单据");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("performanceAnalysis:export")
    @RequestMapping("/performanceAnalysis/exportDetailByGoods")
    public ResponseData exportDetailByGoods(String userId,
                                            String storeId,
                                            String date1,
                                            String date2,
                                            String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<PerformanceAnalysis> list = performanceAnalysisService.listDetailByGoods(company.getId(),
                null,
                null,
                userId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));


        List<ExcelPerformanceAnalysisGoods> excelList = new ArrayList<>();
        for (PerformanceAnalysis entity : list) {
            ExcelPerformanceAnalysisGoods excel = new ExcelPerformanceAnalysisGoods();
            excel.setNo(entity.getNo());
            excel.setName(entity.getName());
            excel.setNorms(entity.getNorms());
            excel.setUnitName(entity.getUnitName());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(),businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excel.setRefundNum(PdosUtils.getNumber(entity.getRefundNum(),businessSet));
            excel.setRefundAmt(PdosUtils.getPrice(entity.getRefundAmt(), businessSet));
            excelList.add(excel);
        }


        String excelName = "业绩统计按商品列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";

        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelPerformanceAnalysisGoods.class);
            sheet1.setSheetName("业绩统计按商品列表");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

}
